package com.my.screenadapter.net.volley;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.my.screenadapter.MyApplication;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ${张英杰} on 2017/5/14.
 */
public class VolleyUtils {
    private static RequestQueue requestQueue;

    public static RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            requestQueue=Volley.newRequestQueue(MyApplication.getContext());
        }
        return requestQueue;
    }

    public static void postJSON(String url, String jsonObject, Response.Listener listener, Response.ErrorListener errorListener) {
        getRequestQueue();
        JSONObject temp=null;
        try {
            temp= new JSONObject(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,temp , listener, errorListener) {

            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> headers = new HashMap<String, String>();
//                headers.put("Accept", "application/json");
//                headers.put("Content-Type", "application/json; charset=UTF-8");
                headers.put("Content-Type", "text/json; charset=UTF-8");
                return headers;
            }
        };
        requestQueue.add(request);
    }

    //带token的请求
    public static void getTokenRequest(String url, final String token, Response.Listener listener, Response.ErrorListener errorListener) {
        getRequestQueue();
        StringRequest request = new StringRequest(Request.Method.GET, url ,listener, errorListener) {

            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> headers = new HashMap<String, String>();
//                headers.put("Accept", "application/json");
//                headers.put("Content-Type", "application/json; charset=UTF-8");
                headers.put("token", token);
                return headers;
            }
        };
        requestQueue.add(request);
    }

}
